<template>
  <div>
    <el-upload
      :class="{ disabled: count === limit }"
      :file-list="fileList"
      :action="action"
      :headers="headers"
      :list-type="listType"
      :limit="limit"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="handleBeforeUpload"
      :disabled="disabled"
    >
      <i v-if="listType === 'picture-card'" class="el-icon-plus" />
      <el-button v-else size="small" type="primary">点击上传</el-button>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { div } from '@/utils/number'
const isProd = process.env.NODE_ENV === 'production'
export default {
  name: 'MyUpload',
  model: { // 负责将对应的事件值传给父组件v-model绑定的变量
    prop: 'fileList',
    event: 'uploadEnd' // 这个触发事件对应元素自身的事件，比如输入框就是input
  },
  props: {
    fileList: {
      type: Array,
      default: () => {
        return []
      }
    },
    limit: { // 上传上限
      type: Number,
      default: 1
    },
    disabled: {
      type: Boolean,
      default: false
    },
    listType: { // 图片列表展示类型
      type: String,
      default: 'picture-card' // text/picture/picture-card
    },
    action: { // 上传图片的地址
      type: String,
      default: isProd ? 'https://jn.speschool.com/api/upload/upload' : 'http://192.168.0.88:19999/api/upload/upload'
    },
    maxSize: { // 图片最大限制，单位为M
      type: Number,
      default: null
    },
    imgType: { // 允许的图片格式
      type: String,
      default: 'jpg, jpeg, png, gif'
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      count: 0,
      headers: {
        token: localStorage.token
      }
    }
  },
  computed: {
    imgTypeList() {
      return this.imgType.split(',').map(v => v.trim().toLocaleLowerCase())
    }
  },
  methods: {
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    },
    handleRemove(file, fileList) {
      const arr = []
      fileList.forEach(v => {
        arr.push({
          name: v.name,
          url: v.response ? v.response.result : v.url
        })
      })
      this.count = this.count - 1
      if (this.handleChange && typeof this.handleChange === 'function') {
        this.handleChange(arr)
      } else {
        this.$emit('uploadEnd', arr)
      }
    },
    handlePictureCardPreview(file) {
      if (this.listType !== 'text') {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      }
    },
    handleSuccess(response, file, fileList) {
      if (response.code === 999) {
        this.$message.error(response.desc)
        this.logout()
      } else if (response.code === 100) {
        const arr = []
        fileList.forEach(v => {
          arr.push({
            name: v.name,
            url: v.response ? v.response.result : v.url
          })
        })
        this.count = this.count + 1
        this.$emit('uploadEnd', arr)
        this.$emit('transferResponse', response)
      }
    },
    handleBeforeUpload(file) {
      // 检查大小是否符合条件
      let isLimit = true
      let isTrueType = false
      if (this.maxSize && div(div(file.size, 1024), 1024) > this.maxSize) {
        isLimit = false
      }
      if (!isLimit) {
        this.$message.error(`单个文件不能超过${this.maxSize}M!`)
      }
      // 检查要求的图片格式
      this.imgTypeList.forEach(v => {
        if (file.name.indexOf(`.${v.toLocaleLowerCase()}`) >= 0) {
          isTrueType = true
        }
      })
      if (!isTrueType) {
        this.$message.error(`只能上传${this.imgType}格式的文件!`)
      }
      return isTrueType && isLimit
    }
  }
}
</script>

<style lang="less" scoped>
  .disabled ::v-deep .el-upload.el-upload--picture-card {
    display: none;
  }
</style>
